from pathlib import Path
from typing import Dict, Optional
from .base import BaseTTSEngine


class Pyttsx3TTSEngine(BaseTTSEngine):
    """
    pyttsx3本地TTS引擎实现
    """
    
    def __init__(self, config: Optional[Dict] = None):
        super().__init__(config)
        self.has_pyttsx3 = False
        self.pyttsx3 = None
        self.engine = None
        self.initialize()
    
    def initialize(self) -> bool:
        """
        初始化pyttsx3引擎
        """
        try:
            import pyttsx3
            self.pyttsx3 = pyttsx3
            self.has_pyttsx3 = True
            
            # 尝试初始化引擎
            try:
                self.engine = self._create_engine()
                if self.engine:
                    self.initialized = True
                    print("✓ pyttsx3引擎初始化成功")
                    return True
            except Exception as init_error:
                print(f"✗ pyttsx3引擎初始化失败: {init_error}")
                return False
        except ImportError:
            print("✗ pyttsx3引擎初始化失败: 未安装pyttsx3库")
            return False
    
    def _create_engine(self):
        """
        创建pyttsx3引擎实例，尝试多种驱动
        """
        # 尝试不同的初始化方式
        try:
            # macOS上优先尝试使用nsss驱动
            import platform
            if platform.system() == "Darwin":
                return self.pyttsx3.init(driverName='nsss')
        except Exception:
            pass
        
        try:
            # 尝试默认初始化
            return self.pyttsx3.init()
        except Exception:
            pass
        
        try:
            # 尝试使用espeak驱动
            return self.pyttsx3.init(driverName='espeak')
        except Exception:
            return None
    
    def synthesize(self, text: str, output_path: Path, lang: str = "en") -> bool:
        """
        使用pyttsx3进行语音合成
        """
        if not self.is_available():
            print(f"  ⚠ pyttsx3引擎不可用，无法合成文本: {text}")
            return False
        
        try:
            # 如果引擎不可用，重新创建
            if not self.engine:
                self.engine = self._create_engine()
                if not self.engine:
                    return False
            
            # 设置语速和音量
            rate = self.config.get('rate', 150)
            volume = self.config.get('volume', 0.9)
            self.engine.setProperty('rate', rate)
            self.engine.setProperty('volume', volume)
            
            # 设置语言
            try:
                voices = self.engine.getProperty('voices')
                # 尝试找到对应语言的语音
                for voice in voices:
                    if lang in voice.id.lower():
                        self.engine.setProperty('voice', voice.id)
                        break
            except Exception as voice_error:
                print(f"  ⚠ pyttsx3语音设置失败: {voice_error}")
            
            # 保存到文件
            self.engine.save_to_file(text, str(output_path))
            self.engine.runAndWait()
            
            print(f"  ✓ 生成音节语音: {text} -> {output_path.name} (pyttsx3)")
            return True
        except Exception as e:
            print(f"  ⚠ pyttsx3失败: {e}")
            return False
    
    def is_available(self) -> bool:
        """
        检查pyttsx3引擎是否可用
        """
        return self.has_pyttsx3 and self.initialized
    
    def get_name(self) -> str:
        """
        获取引擎名称
        """
        return "pyttsx3"
    
    def cleanup(self):
        """
        清理pyttsx3引擎资源
        """
        if self.engine:
            try:
                self.engine.stop()
            except Exception:
                pass
            self.engine = None